<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view class="container">
		<!-- 顶部导航 -->
		<custom-nav-tabs>
			<!-- 可自定义左侧图标 -->
			<template #left>
				<view class="nav-left" @click="onperson">
					<view style="padding-right: 0rpx;">
						<uni-icons type="back" size="28" color="#ff0000" />
					</view>
					<view style="font-weight: bold;">
						第{{videosEpisodes}}集
					</view>
				</view>
			</template>
			<!-- 可自定义右侧内容 -->
			<template #right>
				<view style="width: 60rpx;"></view>
			</template>
		</custom-nav-tabs>

		<view class="video-swiper">
			<!-- 全屏 Swiper 容器 -->
			<swiper class="video-swiper" :current="currentIndex" @change="onSwiperChangeThrottled" vertical
				:duration="150">
				<!-- 控制只渲染当前索引前后3个视频，防止内存溢出 -->
				<swiper-item v-for="(item,index) in videos" :key="item.id" class="swiper-item">
					<view class="video-wrapper" @tap="togglePlay(item.id)" v-if="isVideoVisible(index)">
						<!-- 视频播放器 -->
						<video :id="'MyPlayer' + item.id" :src="item.videoUrl" :show-mute-btn="true"
							:show-play-btn="true" :show-fullscreen-btn="false" auto-pause-if-navigate
							:auto-pause-if-navigate="true" :auto-pause-if-open-native="true" auto-pause-if-open-native
							controls class="fullscreen-video" @play="onPlay(item.id)" @pause="onPause(item.id)"
							@ended="onEnded(item.id)" @error="onVideoError" @waiting="onwaiting">
							<!-- 开通会员的提示 -->
							<view class="video-center" v-if="showVipModal">
								<view class="center-title">本片是由平台VIP会员专享内容</view>
								<view class="center-title2">试看已结束，继续观看请开通VIP会员</view>
								<view @click.stop="huiyuanFunction" class="center-text">开通会员</view>
							</view>
						</video>

						<!-- 短剧相关的信息 -->
						<view class="video-c-title">
							<view class="v-title">{{item.collectionPlays[0].name}}</view>
							<view class="v-tags">
								<view>{{item.collectionPlays[0].tagsName}}</view>
								<view>｜</view>
								<view>第{{item.videoJi}}集</view>
							</view>

						</view>

						<!-- 自定义播放/暂停图标 -->
						<!-- <view class="play-pause-icon" v-if="playingId !== item.id">
							<image v-if="!showVipModal" src="/static/icon/of-s.png" />
						</view> -->
						<!-- 转发，评论 -->
						<SocialActions :episode="true" :videoContent="currentIndex ? videos[currentIndex] : videos[0]"
							@select-episode="handleSelectEpisode" />

					</view>
				</swiper-item>
			</swiper>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue'
	import {
		PlayVideosUrl,
		updadeVideosCreate
	} from '@/API/ofPlayApis.js';
	import CustomNavTabs from '@/components/ofPlay/CustomNavTabs.vue'
	import SocialActions from '@/components/ofPlay/SocialActions.vue';
	import {
		onReachBottom,
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	const loading = ref(true)
	// 先获取用户信息然后进行存储
	// #ifdef MP-WEIXIN
	const user = ref(null);
	// #endif
	// 获取演员信息
	onLoad((e) => {
		console.log("videoID：", e.id);
		console.log("开始加载第一页数据:", e);
		loadMoreData(e.id)
		videoId.value = e.id;
		if (e?.episodes) {
			currentIndex.value = e.episodes - 1;
			videosEpisodes.value = e.episodes;
		}

		if (e?.scene) {
			const sceneParams = parseScene(e.scene);
			const id = sceneParams.id;
			const userId = sceneParams.userId;
			loadMoreData(id)
			videoId.value = id;
			console.log('id:', id, 'userId:', userId);
			uni.setStorageSync("ShareUserId", userId);
		}



	})
	// 解析scane数据
	function parseScene(scene) {
		try {
			const decoded = decodeURIComponent(scene);
			const params = {};
			decoded.split('&').forEach(pair => {
				const [key, val] = pair.split('=');
				if (key && val) {
					params[key] = decodeURIComponent(val);
				}
			});
			return params;
		} catch (e) {
			console.error('解析 scene 失败:', e);
			return {};
		}
	}

	onShow(() => {
		// #ifdef MP-WEIXIN
		console.log("用户数据已更新")
		user.value = uni.getStorageSync("user");
		console.log("userSync:", user.value)
		if (user.value.status == 1) {
			showVipModal.value = false
		}
		// #endif


	})

	const showVipModal = ref(false) // 开通会员的提示

	// 数据分页配置
	const pageNum = ref(1) //短剧下一页
	const loadingMore = ref(false)
	const navIndexValue = ref([]);
	const videosEpisodes = ref(1);
	const wchatVideos = ref()

	// 当前播放索引
	const currentIndex = ref(0)
	const playingId = ref(null)
	const isPlaying = ref(false)
	const playIcon = ''
	const pauseIcon = '/static/icon/of-s.png'
	const videoId = ref();

	// 视频数据（分页加载）
	const videos = ref([]);

	// 视频上下文对象
	const videoContexts = ref({});

	// 触底刷新
	onReachBottom(() => {


	})

	// 方法：判断当前视频是否可见（前后3个）
	const isVideoVisible = (index) => {
		const diff = Math.abs(index - currentIndex.value)
		return diff <= 3 // 仅渲染当前播放视频及其前后各1个视频
	}


	// 定义节流函数，用于限制函数调用频率
	const throttle = (fn, delay) => {
		let lastTime = 0
		return function(...args) {
			const now = Date.now()
			if (now - lastTime >= delay) {
				fn.apply(this, args)
				lastTime = now
			}
		}
	}

	// 定义防抖函数，用于减少不必要的函数调用
	const debounce = (fn, delay) => {
		let timer = null
		return function(...args) {
			if (timer) clearTimeout(timer)
			timer = setTimeout(() => {
				fn.apply(this, args)
			}, delay)
		}
	}

	// 优化后的视频上下文创建函数，添加防抖处理
	const createVideoContextDebounced = debounce((id) => {
		if (!videoContexts.value[id]) {
			videoContexts.value[id] = uni.createVideoContext('MyPlayer' + id)
		}
	}, 300)

	// 优化 onSwiperChange 函数，添加节流处理
	const onSwiperChangeThrottled = throttle((e) => {
		const newIndex = e.detail.current
		const oldId = videos.value[currentIndex.value]?.id

		// 暂停旧视频
		if (oldId && videoContexts.value[oldId]) {
			videoContexts.value[oldId].pause()
		}

		pauseOtherVideos(oldId)

		currentIndex.value = newIndex

		// 获取当前视频 ID
		const newId = videos.value[newIndex]?.id
		videosEpisodes.value = videos.value[newIndex]?.videoJi
		wchatVideos.value = videos.value[newIndex]

		// 创建当前视频上下文（如果不存在）
		if (newId) {
			createVideoContextDebounced(newId)
		}

		// 预加载前后 2 个视频的上下文
		const preloadRange = 3
		const start = Math.max(0, newIndex - preloadRange)
		const end = Math.min(videos.value.length - 1, newIndex + preloadRange)

		for (let i = start; i <= end; i++) {
			const id = videos.value[i]?.id
			if (id) {
				createVideoContextDebounced(id)
			}
		}


		const status = videos.value[newIndex]?.status
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user")
		let userStatus = user.status
		if (userStatus === 1) {
			// 自动播放
			if (newId) {
				play(newId)
			}
			// 清理超出范围的视频和上下文
			cleanUpOldVideos(newIndex)
			return
		}
		if (status === 2) {
			console.log("status执行了")
			showVipModal.value = true
			if (videoContexts.value[newId]) {
				videoContexts.value[newId].pause()
			}
		} else {
			// 自动播放
			if (newId) {
				play(newId)
			}
			// 清理超出范围的视频和上下文
			cleanUpOldVideos(newIndex)
			showVipModal.value = false
		}
		// #endif
	}, 300)


	// 方法：播放视频
	const play = (id) => {
		if (!videoContexts.value[id]) {
			videoContexts.value[id] = uni.createVideoContext('MyPlayer' + id)
		}

		const context = videoContexts.value[id]
		if (context) {
			playingId.value = id
			isPlaying.value = true

			// 增加 setTimeout 延迟播放，解决上下文创建延迟问题
			setTimeout(() => {
				context.play()
			}, 50)
		}
	}

	// 方法：暂停视频
	const pause = (id) => {
		const context = videoContexts.value[id]
		if (context) {
			context.pause()
		}
		isPlaying.value = false
	}

	// 方法：切换播放/暂停
	const togglePlay = (id) => {
		if (showVipModal.value) {
			return;
		}
		if (playingId.value === id) {
			pause(id)
			playingId.value = null
			isPlaying.value = false
		} else {
			if (playingId.value && videoContexts.value[playingId.value]) {
				videoContexts.value[playingId.value].pause()
				isPlaying.value = false
			}
			play(id)
			isPlaying.value = true
		}
	}
	const isVideoLoading = ref(false);
	const onwaiting = () => {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
		// isVideoLoading.value = true;
		// // 3秒后强制隐藏提示（防止未触发onPause）
		// setTimeout(() => {
		// 	if (isVideoLoading.value) {
		// 		uni.hideLoading();
		// 		isVideoLoading.value = false;
		// 	}
		// }, 2000)
	}

	// 方法：视频播放开始
	const onPlay = (id) => {
		if (isVideoLoading.value) {
			uni.hideLoading();
			isVideoLoading.value = false;
		}
		playingId.value = id
		isPlaying.value = true
	}


	// 方法：视频暂停
	const onPause = (id) => {
		uni.hideLoading()
		if (playingId.value === id) {
			playingId.value = null
			isPlaying.value = false
		}
	}

	// 方法：视频播放结束，自动播放下一个
	const onEnded = (id) => {
		const index = videos.value.findIndex(v => v.id === id)
		if (index < videos.value.length - 1) {
			currentIndex.value = index + 1
			setTimeout(() => {
				play(videos.value[currentIndex.value].id)
			}, 100)
		}
	}

	const MAX_VIDEO_CACHE = 200;
	const playHistory = []; // 播放记录，用于 LRU 缓存策略

	const loadMoreData = async (page) => {

		// if (!page) {
		// 	uni.showToast({
		// 		title: '加载失败！'
		// 	});
		// 	return;
		// }

		try {
			// #ifdef MP-WEIXIN
			let user = uni.getStorageSync("user");
			let userId = user.id;
			console.log("用户信息:", user);
			console.log("userId:", userId);
			// #endif
			const res = await PlayVideosUrl(userId, page);
			console.log("数据：", res);
			const newVideos = res.list;
			// 使用 Map 合并新旧数据，id 相同则合并（新数据覆盖旧数据）
			const videoMap = new Map();
			videos.value.forEach(video => {
				videoMap.set(video.id, video);
			});

			newVideos?.forEach(video => {
				videoMap.set(video.id, video);
			});

			videos.value = Array.from(videoMap.values());

			// // 用于缓存管理的视频 id 列表（排除当前播放的）
			const currentVideoId = videos.value[currentIndex.value]?.id;
			const cacheableVideos = videos.value.filter(v => v.id !== currentVideoId);

			// 优先释放未播放过的视频上下文
			while (Object.keys(videoContexts.value).length >= MAX_VIDEO_CACHE) {
				let idToRemove = null;

				// 	// 找一个不在播放记录中的视频
				for (let i = 0; i < cacheableVideos.length; i++) {
					if (!playHistory.includes(cacheableVideos[i].id)) {
						idToRemove = cacheableVideos[i].id;
						break;
					}
				}

				// 	// 如果没找到，就找最早播放的
				if (!idToRemove && playHistory.length > 0) {
					idToRemove = playHistory[0];
				}

				// 	// 如果都没找到，随便选一个
				if (!idToRemove) {
					idToRemove = Object.keys(videoContexts.value).find(id => id !== currentVideoId) || null;
				}

				if (idToRemove && videoContexts.value[idToRemove]) {
					videoContexts.value[idToRemove].pause();
					videoContexts.value[idToRemove] = null;
					delete videoContexts.value[idToRemove];
					console.log("已释放视频上下文：", idToRemove);
				} else {
					break;
				}
			}

			// 更新播放历史
			if (currentVideoId && !playHistory.includes(currentVideoId)) {
				playHistory.push(currentVideoId);
				if (playHistory.length > 15) {
					playHistory.shift();
				}
			}

			await nextTick();

			// ✅ 创建新视频的上下文
			newVideos.forEach((item) => {
				if (!videoContexts.value[item.id]) {
					videoContexts.value[item.id] = uni.createVideoContext('MyPlayer' + item.id);
				}
			});

			// ✅ 主动为第一个视频创建上下文（即使它不是新视频）
			const firstVideo = videos.value[0];
			if (firstVideo && !videoContexts.value[firstVideo.id]) {
				videoContexts.value[firstVideo.id] = uni.createVideoContext('MyPlayer' + firstVideo.id);
			}

			// pageNum.value = res.nextPage;
			// console.log("当前缓存上下文 id 列表：", Object.keys(videoContexts.value));

			loading.value = false


		} catch (error) {
			console.error('加载数据失败:', error);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		} finally {
			loadingMore.value = false;
		}
	};
	// 清理不适用的上下文
	const cleanUpOldVideos = (currentIndex) => {
		const visibleRange = {
			start: Math.max(0, currentIndex - 1),
			end: Math.min(videos.value.length - 1, currentIndex + 1)
		}

		// 保留上下文缓存，只清理超出范围的
		Object.keys(videoContexts.value).forEach(id => {
			const index = videos.value.findIndex(v => v.id === parseInt(id))
			if (index !== -1 && (index < visibleRange.start || index > visibleRange.end)) {
				// 暂停并清理上下文
				videoContexts.value[id].pause()
				delete videoContexts.value[id]
			}
		})
	}
	// 播放异常
	const onVideoError = (e) => {
		uni.hideLoading()
		uni.showToast({
			title: '视频加载失败',
			icon: 'none'
		})
	}

	function pauseOtherVideos(currentId) {
		Object.keys(videoContexts.value).forEach(id => {
			if (id !== currentId && videoContexts.value[id]) {
				videoContexts.value[id].pause();
			}
		});
	}
	// 选集播放
	const handleSelectEpisode = (episode) => {
		const index = videos.value.findIndex(v => v.id === episode.id);
		if (index !== -1) {
			currentIndex.value = index;
			// 触发 swiper change 事件（或手动播放）
			play(episode.id);
		}
	}

	// 图标导航栏
	function onperson() {

		if (wchatVideos.value) {
			console.log("wchatVideos:", wchatVideos.value)
			console.log("记录：", user.value.id, wchatVideos.value.id, wchatVideos.value.videoId, wchatVideos.value.videoJi)
			updateCreateFunction(user.value.id, wchatVideos.value.id, wchatVideos.value.videoId, wchatVideos.value.videoJi)
			console.log("观看记录已存储！")
		}


		// 获取当前页面栈
		const pages = getCurrentPages()
		console.log('当前页面栈:', pages.length)
		if (pages.length > 1) {
			uni.navigateBack({
				delta: 1 // 返回上一个页面
			});
		} else {
			// 已经是第一页，不能返回
			// 可以选择关闭小程序或跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	}


	// 观看记录
	const updateCreateFunction = async (userId, urlId, videoId, episodesCount) => {
		let res = await updadeVideosCreate(userId, urlId, videoId, episodesCount);
		console.log("观看记录已更新")
	}

	// video中的会员按钮
	function huiyuanFunction() {
		uni.navigateTo({
			url: '/pages/alpay/playAlpay/playAlpay'
		})
	}
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background-color: black;
	}

	.navBottum {
		/* 顶部导航占位 */
	}

	.video-center {
		background: #1d1d1d;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		z-index: 100;
	}

	.center-text {
		background: #ff0000;
		padding: 30rpx;
		box-sizing: border-box;
		border-radius: 20rpx;
	}

	.center-title2 {
		font-size: 22rpx;
		color: #464646;
		padding: 30rpx 0;
	}

	.center-title {
		padding: 20rpx 0;
	}

	.video-swiper {
		width: 100%;
		height: 100%;
	}

	.swiper-item {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.video-wrapper {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.fullscreen-video {
		width: 100%;
		height: 100%;
		background-color: black;
	}

	.play-pause-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 60px;
		height: 60px;
		z-index: 50;
		opacity: 0.7;
	}

	.play-pause-icon image {
		width: 100%;
		height: 100%;
	}

	.loading {
		text-align: center;
		padding: 10px;
		color: white;
	}

	.nav-left {
		margin-left: -20rpx;
		width: 200rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;

	}


	.video-c-title {
		pointer-events: auto;
		width: 100%;
		position: fixed;
		bottom: 70rpx;
		z-index: 10;

	}

	.v-title {
		font-size: 28rpx;
		font-weight: bold;
		padding: 0 30rpx;
	}

	.v-tags {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		padding: 10rpx 30rpx;
	}
</style>